package com.cta.view.model.discount;

import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;

import com.cta.entity.DiscountRate;
import com.cta.utils.VietCalendarUtils;
import com.cta.view.model.CallData;

public class DateDiscountModel extends DiscountModel {

	private LocalDate date;

	private static final DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendDayOfMonth(2)
			.appendLiteral('/').appendMonthOfYear(2).appendLiteral('/').appendYear(4, 4).toFormatter();

	public DateDiscountModel(DiscountRate orgDiscount) {
		super(orgDiscount);
		// parsing date
		if (orgDiscount.getDateType().equals("AL")) {
			LocalDate tempDate = LocalDate.parse(orgDiscount.getCondition(), formatter);
			int[] lunar2Solar = VietCalendarUtils.convertLunar2Solar(tempDate.dayOfYear().get(), tempDate.monthOfYear()
					.get(), tempDate.year().get(), 7.0);
			if (lunar2Solar != null && lunar2Solar.length >= 3) {
				date = new LocalDate(lunar2Solar[2], lunar2Solar[1], lunar2Solar[0]);
				date = date.withYear(0);
			}
		} else {
			date = LocalDate.parse(orgDiscount.getCondition(), formatter);
			date = date.withYear(0);
		}
	}
	
	public DateDiscountModel(DiscountRate orgDiscount, int discountVal) {
		super(orgDiscount, discountVal);
		// parsing date
		if (orgDiscount.getDateType().equals("AL")) {
			LocalDate tempDate = LocalDate.parse(orgDiscount.getCondition(), formatter);
			int[] lunar2Solar = VietCalendarUtils.convertLunar2Solar(tempDate.dayOfMonth().get(), tempDate.monthOfYear()
					.get(), tempDate.year().get(), 7.0);
			if (lunar2Solar != null && lunar2Solar.length >= 3) {
				date = new LocalDate(lunar2Solar[2], lunar2Solar[1], lunar2Solar[0]);
				date = date.withYear(0);
			}
		} else {
			date = LocalDate.parse(orgDiscount.getCondition(), formatter);
			date = date.withYear(0);
		}
	}

	@Override
	public void hasDiscount(CallData data) throws Exception {
		LocalDate startDate = data.getStartDate().toLocalDate().withYear(0);
		LocalDate endDate = data.getEndDate().toLocalDate().withYear(0);
		if (date.compareTo(startDate) >= 0 && date.compareTo(endDate) <= 0) {
			log.info(String.format("Has date discount-> date: %s, callStartDate: %s, callEndDate", date, startDate,
					endDate));
			data.getDayDiscounts().put(date.toString(), this);
		}
	}
}
